﻿using Microsoft.AspNetCore.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;

namespace SSRS.Core.Application.Web
{
    /// <summary>
    /// 版 本 ADMS 2.0 开发框架
    /// Copyright (c) 2013-2019 
    /// 创建人：徐志强
    /// 日 期：2018年12月6日14:15:39
    /// 仅允许Ajax操作
    /// </summary>
    [AttributeUsage(AttributeTargets.Method)]
    public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
    {
        /// <summary>
        /// 初始化仅允许Ajax操作
        /// </summary>
        /// <param name="ignore">跳过Ajax检测</param>
        public AjaxOnlyAttribute(bool ignore = false)
        {
            Ignore = ignore;
        }

        /// <summary>
        /// 跳过Ajax检测
        /// </summary>
        public bool Ignore { get; set; }

        /// <summary>
        /// 验证请求有效性
        /// </summary> 
        /// <param name="routeContext">控制器上下文</param>
        /// <param name="action">方法</param>
        public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
        {
            if (Ignore)
                return true;
            var requestedWith = routeContext.HttpContext.Request.Headers["X-Requested-With"];
            string method = routeContext.HttpContext.Request.Method;

            if (method.ToUpper() == "POST" || method.ToUpper() == "GET")
            {
                if (requestedWith == "XMLHttpRequest")
                {
                    return true;
                }
            }

            return false;
        }
    }
}
